package com.zhouyibike.uu.ui.activity.mywallet;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.gyf.barlibrary.OnKeyboardListener;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.LoginResult;
import com.zhouyibike.uu.entity.TwentyActivityResult;
import com.zhouyibike.uu.entity.YCQResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.activity.YanzhengActivity;
import com.zhouyibike.uu.ui.activity.mybike.Twentyoffer.Buy20SuccessActivity;
import com.zhouyibike.uu.ui.activity.mybike.Twentyoffer.PayActivity20;
import com.zhouyibike.uu.ui.activity.yihoudong.YihuodongActivity3;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.utils.PermissionTool;
import com.zhouyibike.uu.utils.Util;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import observablescrollview.ObservableScrollView;
import observablescrollview.ObservableScrollViewCallbacks;
import observablescrollview.ScrollState;

public class MyWalletActivity4 extends BaseActivity implements View.OnClickListener, ObservableScrollViewCallbacks {
    private ObservableScrollView mywalletobscroll;
    private LinearLayout mywallettitle;
    private ImageView fanhui, lvka, goyihuodong, duihuan;
    private TextView qixingquannum, ketixiantv, qixingyue, chakanqixingquan, chakanqixingyue, gotixian,mingxi;
    private List<TwentyActivityResult.DataBean.ImagesBean> imagesBeen = new ArrayList<>();
    private int shengche = 0;
    private boolean hasbuy20danche = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_wallet4);
//        settitle();
        imagesBeen = (List<TwentyActivityResult.DataBean.ImagesBean>) getIntent().getSerializableExtra("chong20");
        shengche = getIntent().getIntExtra("shengche20", 0);
        has20danche();
        initView();
        initlistener();
        reloadAccountInfo();
    }
    private void has20danche() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        addSubscription(apiStores.TwentyActivity(params),
                new ApiCallback<TwentyActivityResult>() {
                    @Override
                    public void onSuccess(TwentyActivityResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            hasbuy20danche = model.getData().isSuccess();
                            shengche = model.getData().getAmount();
                        } else {
                            toastShow(model.getMessage());
                        }
                    }
                    @Override
                    public void onFailure(String msg) {
                    }
                    @Override
                    public void onFinish() {

                    }
                });
    }
    private void initlistener() {
        lvka.setOnClickListener(this);
        fanhui.setOnClickListener(this);
        mywalletobscroll.setScrollViewCallbacks(this);
        chakanqixingquan.setOnClickListener(this);
        chakanqixingyue.setOnClickListener(this);
        gotixian.setOnClickListener(this);
        goyihuodong.setOnClickListener(this);
        duihuan.setOnClickListener(this);
        mingxi.setOnClickListener(this);
    }

    private void initView() {
        duihuan = (ImageView) findViewById(R.id.duihuan);
        goyihuodong = (ImageView) findViewById(R.id.goyihuodong);
        lvka = (ImageView) findViewById(R.id.lvka);
        gotixian = (TextView) findViewById(R.id.gotixian);
        chakanqixingquan = (TextView) findViewById(R.id.chakanqixingquan);
        ketixiantv = (TextView) findViewById(R.id.ketixiantv);
        qixingyue = (TextView) findViewById(R.id.qixingyue);
        qixingquannum = (TextView) findViewById(R.id.qixingquannum);
        fanhui = (ImageView) findViewById(R.id.fanhui);
        mywallettitle = (LinearLayout) findViewById(R.id.mywallettitle);
        mywalletobscroll = (ObservableScrollView) findViewById(R.id.mywalletobscroll);
        chakanqixingyue = (TextView) findViewById(R.id.chakanqixingyue);
        mingxi= (TextView) findViewById(R.id.mingxi);
    }
    private  double adddouble(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }
    /**
     * 重新获取用户信息数据
     */
    private void reloadAccountInfo() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        showProgressDialog();
        addSubscription(apiStores.ReloadAccountInfo(params),
                new ApiCallback<LoginResult>() {

                    @Override
                    public void onSuccess(LoginResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            SharedPreferences.Editor edit = preferences.edit();
                            edit.putString("token", model.getData().getToken());
                            edit.putString("fullName", model.getData().getFullName());
                            edit.putString("headPicture", model.getData().getHeadPicture());
                            edit.putString("nickName", model.getData().getNickName());
                            edit.putString("status", model.getData().getStatus());
                            if (model.getData().getStatus().equals("11") || model.getData().getStatus().equals("3")) {
                                edit.putString("status", "3");
                            }
                            edit.putString("createTime", model.getData().getCreateTime());
                            edit.putBoolean("hasPassword", model.getData().isHasPassword());
                            edit.putString("lastLoginTime", model.getData().getLastLoginTime());
                            edit.putString("minAmountForRiding", model.getData().getMinAmountForRiding());
                            edit.putString("rechargeAmount", model.getData().getRechargeAmount());
                            edit.putString("incomeAmount", model.getData().getIncomeAmount());
                            edit.putString("totalAmount", model.getData().getTotalAmount());
                            edit.putString("yiQuanIncoming", model.getData().getYiQuanIncoming());
                            edit.commit();
                            qixingyue.setText(model.getData().getTotalAmount());
                            try {
                                DecimalFormat df = new DecimalFormat("######0.00");
                                df.setRoundingMode(RoundingMode.DOWN);//都舍
                                ketixiantv.setText(df.format(adddouble(Double.parseDouble(model.getData().getIncomeAmount()),Double.parseDouble(model.getData().getYiQuanIncoming()))));
                            } catch (Exception e) {
                                ketixiantv.setText("0");
                            }

                            if (ketixiantv.getText().toString().length()>=9)
                            {
                                ketixiantv.setTextSize(24);
                            }
//                            settextbigwithstr(ketixiantv, ".");
                        } else if (model.getStatus() == 508 || model.getStatus() == 506 || model.getStatus() == 307) {
                            setResult(2501);
                            finish();
                        }else{
                            toastShow(model.getMessage());
                        }
//                        else if (model.getStatus() == 600) {
//                            SharedPreferences.Editor edit = preferences.edit();
//                            edit.clear();
//                            edit.commit();
//                            startActivity(new Intent(MyWalletActivity.this, YanzhengActivity.class));
//                            finish();
//                        } else {
//                            SharedPreferences.Editor edit = preferences.edit();
//                            edit.clear();
//                            edit.commit();
//                            startActivity(new Intent(MyWalletActivity.this, YanzhengActivity.class));
//                            finish();
//                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
//                        dismissProgressDialog();
                        // zly.startAnimation(getAnimation());//这是第2种方式
//                        walletly1.setAnimation(operatingAnim);
//                        walletly2.setAnimation(operatingAnim);
//                        walletly3.setAnimation(operatingAnim);
//                        walletly4.setAnimation(operatingAnim);
                        try {
                            getMsg();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy(); //必须调用该方法，防止内存泄漏
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fanhui:
                finish();
                break;
            case R.id.gotixian:
                if (preferences.getString("status", "").equals("3")) {
                    startActivityForResult(new Intent(MyWalletActivity4.this, TixiannewActivity2.class), 400);
                } else {
                    startActivity(new Intent(MyWalletActivity4.this, YanzhengActivity.class));
                }
                break;
            case R.id.chakanqixingyue:
//                startActivityForResult(new Intent(MyWalletActivity.this,CZSuccessActivity.class),400);
                if (preferences.getString("status", "").equals("3")) {
                    startActivityForResult(new Intent(MyWalletActivity4.this, ChongZhiActivity.class), 400);
                } else {
                    startActivity(new Intent(MyWalletActivity4.this, YanzhengActivity.class));
                }
                break;
            case R.id.chakanqixingquan:
                startActivityForResult(new Intent(this, MyYHQActivity.class),400);
                break;
            case R.id.mingxi:
                Intent intent = new Intent(this, MyDetailActivity.class);
                intent.putExtra("type", "0");
                startActivity(intent);
                break;
            case R.id.goyihuodong:
                Intent intent2 = new Intent(MyWalletActivity4.this, YihuodongActivity3.class);
                startActivityForResult(intent2,400);
                break;
//            case R.id.walletly_sao://123付款
//                if (PermissionTool.isCameraCanUse()) {
//                    startActivityForResult(new Intent(MyWalletActivity4.this, SaomafukuanActivity.class), 123);
//                } else {
//                    toastShow("没有获取相机权限,请手动设置应用权限");
//                }
//                break;
//            case R.id.walletly_shoukuan://321收款
//                startActivityForResult(new Intent(MyWalletActivity4.this, ShoukuanActivity.class), 321);
//                break;
            case R.id.lvka://绿卡
                if (!hasbuy20danche) {
                    Intent intentchong20 = new Intent(MyWalletActivity4.this, PayActivity20.class);
//                        huodongdanche20
                    intentchong20.putExtra("shengche20", shengche);
                    intentchong20.putExtra("chong20", (Serializable) imagesBeen);
                    startActivityForResult(intentchong20, 1020);//充20活动
                } else {
//                toastShow("你已经买了20单车了");
//                Intent intentchong20 = new Intent(MainActivity.this, PayActivity20.class);
//                intentchong20.putExtra("shengche20",huodongdanche20);
//                intentchong20.putExtra("chong20", (Serializable) imagesBeen);
//                startActivityForResult(intentchong20, 1020);//充20活动
                    Intent i = new Intent(this, Buy20SuccessActivity.class);
                    i.putExtra("shengche20", shengche);
                    i.putExtra("chong20", (Serializable) imagesBeen);
                    startActivity(i);
                }
                break;
            case R.id.duihuan://兑换区
                startActivityForResult(new Intent(MyWalletActivity4.this,JingpinduihuanActivity.class),100);
                break;

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        mBtnBack.setBackground(CommonHelper.tintDrawable(MyWalletActivity2.this, R.mipmap.bar_return,
//                ColorStateList.valueOf(getResources().getColor(R.color.bg_main_white))));
    }

    private void getMsg() {//查看骑行券
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        showProgressDialog();
        addSubscription(apiStores.GetPackages(params),
                new ApiCallback<YCQResult>() {

                    @Override
                    public void onSuccess(YCQResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            qixingquannum.setText(model.getData().size() + "");
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }


    @Override
    protected void onPause() {
        super.onPause();
//        if (mBtnBack != null) {
//            mBtnBack.setBackground(CommonHelper.tintDrawable(mActivity, R.mipmap.bar_return,
//                    ColorStateList.valueOf(getResources().getColor(R.color.back))));
//        }
    }

    private void settextbigwithstr(TextView view, String str) {
//        int fstart=view.getText().toString().indexOf(str);
//        int fend=fstart+str.length();
        int fstart = view.getText().toString().indexOf(str) + 1;
        int fend = view.getText().toString().length();
        SpannableStringBuilder style = new SpannableStringBuilder(view.getText().toString());
        style.setSpan(new AbsoluteSizeSpan(Util.dp2px(this, 12)), fstart, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        view.setText(style);
    }
    private void settitle(){
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT)//4.9
        {}else {
            ImmersionBar.with(this)
                    .transparentStatusBar()  //透明状态栏，不写默认透明色
                    //  .transparentNavigationBar()  //透明导航栏，不写默认黑色(设置此方法，fullScreen()方法自动为true)
                    //   .transparentBar()             //透明状态栏和导航栏，不写默认状态栏为透明色，导航栏为黑色（设置此方法，fullScreen()方法自动为true）
                    .statusBarColor(R.color.qianbaotitle)     //状态栏颜色，不写默认透明色
                    //  .navigationBarColor(R.color.colorPrimary) //导航栏颜色，不写默认黑色
                    //   .barColor(R.color.colorPrimary)  //同时自定义状态栏和导航栏颜色，不写默认状态栏为透明色，导航栏为黑色
                    //  .statusBarAlpha(1f)  //状态栏透明度，不写默认0.0f
//                .navigationBarAlpha(0.4f)  //导航栏透明度，不写默认0.0F
//                .barAlpha(0.3f)  //状态栏和导航栏透明度，不写默认0.0f
                    .statusBarDarkFont(false)   //状态栏字体是深色，不写默认为亮色
                    .flymeOSStatusBarFontColor(R.color.bg_main_white)  //修改flyme OS状态栏字体颜色
                    .fullScreen(false)      //有导航栏的情况下，activity全屏显示，也就是activity最下面被导航栏覆盖，不写默认非全屏
                    //   .hideBar(BarHide.FLAG_HIDE_BAR)  //隐藏状态栏或导航栏或两者，不写默认不隐藏
                    .fitsSystemWindows(true)    //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                    // .supportActionBar(true) //支持ActionBar使用
                    //  .statusBarColorTransform(R.color.orange)  //状态栏变色后的颜色
//                .navigationBarColorTransform(R.color.orange) //导航栏变色后的颜色
//                .barColorTransform(R.color.orange)  //状态栏和导航栏变色后的颜色
//                .removeSupportAllView() //移除全部view支持
                    .navigationBarEnable(true)   //是否可以修改导航栏颜色，默认为true
                    .navigationBarWithKitkatEnable(true)  //是否可以修改安卓4.4和emui3.1手机导航栏颜色，默认为true
                    .fixMarginAtBottom(true)   //已过时，当xml里使用android:fitsSystemWindows="true"属性时,解决4.4和emui3.1手机底部有时会出现多余空白的问题，默认为false，非必须
                    //  .reset()  //重置所以沉浸式参数
                    .keyboardEnable(false)  //解决软键盘与底部输入框冲突问题，默认为false，还有一个重载方法，可以指定软键盘mode
                    .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)  //单独指定软键盘模式
                    // .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED)  //单独指定软键盘模式
                    .setOnKeyboardListener(new OnKeyboardListener() {    //软键盘监听回调
                        @Override
                        public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
//                            LogUtils.e(isPopup);  //isPopup为true，软键盘弹出，为false，软键盘关闭
                        }
                    })
                    .init();  //必须调用方可沉浸式
        }
    }
    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
        int baseColor = getResources().getColor(R.color.qianbaotitle);
//        float alpha = Math.min(1, (float) scrollY / (mParallaxImageHeight-150));
        Log.e("onScrollChanged: ", scrollY + "");
        if (scrollY >= Util.dp2px(this, 44)) {
            mywallettitle.setBackgroundColor(baseColor);
        } else {
            mywallettitle.setBackgroundColor(getResources().getColor(R.color.transparent));
        }

//        ViewHelper.setTranslationY(mImageView, scrollY / 2);
    }

    @Override
    public void onDownMotionEvent() {

    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 400 && resultCode == 1) {
            setResult(1);
            reloadAccountInfo();
        } else if (requestCode == 400 && resultCode == 2) {
            setResult(1);
            finish();
        }else if (requestCode == 400 && resultCode == 189) {
            Log.e("onActivityResult: ","刷新" );
            reloadAccountInfo();
        }else if (requestCode == 400 && resultCode == 886) {
//            setResult(1);
            finish();
        }else if (requestCode == 400 && resultCode == 885) {
//            setResult(1);
//            finish();
            startActivityForResult(new Intent(MyWalletActivity4.this,JingpinduihuanActivity.class),100);
        }else if (requestCode == 1020 && resultCode == 20) {//成功购机买20单车后
            //是否购买过20信息
            has20danche();
            reloadAccountInfo();
        }
    }
}
